import dayjs from "dayjs";
import { resolve } from "path";
import pkg from "./package.json";
import { warpperEnv } from "./build";
import { getPluginsList } from "./build/plugins";
import { include, exclude } from "./build/optimize";
import { UserConfigExport, ConfigEnv, loadEnv } from "vite";

/** 当前执行node命令时文件夹的地址（工作目录） */
const root: string = process.cwd();

/** 路径查找 */
const pathResolve = (dir: string): string => {
  return resolve(__dirname, ".", dir);
};

/** 设置别名 */
const alias: Record<string, string> = {
  "@": pathResolve("src"),
  "@build": pathResolve("build"),
};

const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
};

export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  const { VITE_CDN, VITE_PORT, VITE_COMPRESSION, VITE_PUBLIC_PATH } =
    warpperEnv(loadEnv(mode, root));
  return {
    base: VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias,
    },

    server: {
      // 是否开启 https
      https: false,
      // 端口号
      port: VITE_PORT,
      host: "0.0.0.0",
      // 允许的主机列表，支持 ngrok 等外部访问
      allowedHosts: true,
      // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
      proxy: {
        // 字符串简写写法：http://localhost:5173/foo -> http://localhost:4567/foo
        "/foo": "http://localhost:4567",
        // 带选项写法：http://localhost:5173/api/bar -> http://jsonplaceholder.typicode.com/bar
        // "/api": {
        //   target: "http://127.0.0.1:4523/m1/3855169-0-default/api",
        //   changeOrigin: true,
        //   rewrite: path => path.replace(/^\/api/, "")
        // },
        // 正则表达式写法：http://localhost:5173/fallback/ -> http://jsonplaceholder.typicode.com/
        "^/fallback/.*": {
          target: "http://jsonplaceholder.typicode.com",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/fallback/, ""),
        },
        // 更具体的规则放在前面
        "/api/avd_vulnerabilities": {
          target: "http://175.27.167.221:5000",
          changeOrigin: true,
          configure: (proxy, options) => {
            // proxy 是 'http-proxy' 的实例
          },
        },
        "/api/vulnerability_detail_search": {
          target: "http://175.27.167.221:5000",
          changeOrigin: true,
          configure: (proxy, options) => {
            // proxy 是 'http-proxy' 的实例
          },
        },
        // // 使用 proxy 实例
        // "/api/api2": {
        //   // target: "http://127.0.0.1:4523/m1/3855169-0-default",
        //   // target: "http://124.222.48.226:8099",
        //   target: "http://43.138.191.28:8082",
        //   changeOrigin: true,
        //   configure: (proxy, options) => {
        //   },
        // },
        // 使用 proxy 实例
        "/api": {
          // target: "http://127.0.0.1:4523/m1/3855169-0-default",
          // target: "http://175.27.167.221:8099",
          target: "http://121.43.28.1:5001",
          // target: "http://82.156.2.94:8099",
          changeOrigin: true,
          configure: (proxy, options) => {
            // proxy 是 'http-proxy' 的实例
          },
        },
        // 无回显型漏洞检测代理
        "/cland": {
          target: "http://43.138.191.28:8080",
          changeOrigin: true,
          configure: (proxy, options) => {
            proxy.on("proxyRes", (proxyRes, req, res) => {
              // 移除 X-Frame-Options 头部
              delete proxyRes.headers["x-frame-options"];
              // 设置允许嵌入iframe
              proxyRes.headers["X-Frame-Options"] = "ALLOWALL";
            });
          },
        },
      },
    },
    plugins: getPluginsList(command, VITE_CDN, VITE_COMPRESSION),
    // https://cn.vitejs.dev/config/dep-optimization-options.html#dep-optimization-options
    optimizeDeps: {
      include,
      exclude,
    },
    build: {
      sourcemap: command === "serve", // 只在开发环境生成 source map，生产环境不生成
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 4000,
      rollupOptions: {
        input: {
          index: pathResolve("index.html"),
        },
        // 静态资源分类打包
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
        },
      },
    },
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
  };
};
